import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as taskApi from '../apis/task'
import * as deviceApi from '../apis/device'

// 任务状态映射
const taskStatusMap = {
  0: { label: '待执行', type: 'info' },
  1: { label: '执行中', type: 'warning' },
  2: { label: '已完成', type: 'success' },
  3: { label: '失败', type: 'danger' }
}

// 任务类型选项
const taskTypeOptions = [
  { label: '频段优化', value: '频段优化' },
  { label: '功率调整', value: '功率调整' },
  { label: '信道分配', value: '信道分配' },
  { label: '天线调优', value: '天线调优' },
  { label: '参数优化', value: '参数优化' }
]

// 设备类型选项
const deviceTypeOptions = [
  { label: '基站', value: '基站' },
  { label: '路由器', value: '路由器' },
  { label: '交换机', value: '交换机' },
  { label: '中继器', value: '中继器' },
  { label: '网关', value: '网关' }
]

export const useTask = () => {
  // 任务列表相关状态
  const taskList = ref([])
  const loading = ref(false)
  const total = ref(0)
  const queryParams = reactive({
    page: 1,
    size: 10,
    taskName: '',
    taskType: '',
    status: ''
  })

  // 任务表单相关状态
  const taskForm = reactive({
    id: '',
    taskName: '',
    deviceId: '',
    deviceType: '', // 添加设备类型字段
    userId: 1, // 默认用户ID
    taskType: '',
    parameters: '{}',
    status: 0
  })
  const formVisible = ref(false)
  const formLoading = ref(false)
  
  // 设备相关状态
  const deviceList = ref([])
  const deviceLoading = ref(false)
  const selectedDevice = ref(null)

  // 获取任务列表
  const fetchTaskList = async () => {
    loading.value = true
    try {
      const response = await taskApi.getTaskList(queryParams)
      taskList.value = response.data.records || []
      total.value = response.data.total || 0
    } catch (error) {
      console.error('获取任务列表失败:', error)
      ElMessage.error('获取任务列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 获取设备列表
  const fetchDeviceList = async (deviceType = '') => {
    deviceLoading.value = true
    try {
      const response = await deviceApi.getDeviceList({ deviceType })
      // 确保设备列表数据正确处理，对于没有name字段的设备，使用其他字段或默认值
      deviceList.value = (response.data.records || []).map(device => ({
        ...device,
        name: device.name || device.deviceName || device.device_id || `设备${device.id}`
      }))
    } catch (error) {
      console.error('获取设备列表失败:', error)
      ElMessage.error('获取设备列表失败')
    } finally {
      deviceLoading.value = false
    }
  }
  
  // 设备类型改变时获取对应设备列表
  const handleDeviceTypeChange = async (deviceType) => {
    taskForm.deviceId = ''
    selectedDevice.value = null
    if (deviceType) {
      await fetchDeviceList(deviceType)
    } else {
      deviceList.value = []
    }
  }
  
  // 设备选择改变时设置deviceId
  const handleDeviceChange = (device) => {
    if (device) {
      taskForm.deviceId = device.id
      selectedDevice.value = device
    } else {
      taskForm.deviceId = ''
      selectedDevice.value = null
    }
  }

  // 搜索任务
  const handleSearch = () => {
    queryParams.page = 1
    fetchTaskList()
  }

  // 重置搜索
  const handleReset = () => {
    Object.assign(queryParams, {
      page: 1,
      size: 10,
      taskName: '',
      taskType: '',
      status: ''
    })
    fetchTaskList()
  }

  // 打开添加任务对话框
  const handleAdd = () => {
    Object.assign(taskForm, {
      id: '',
      taskName: '',
      deviceId: '',
      deviceType: '',
      userId: 1,
      taskType: '',
      parameters: JSON.stringify({
        "frequency": "2400MHz",
        "power": "20dBm",
        "channel": 6,
        "bandwidth": "20MHz",
        "beamforming": true
      }, null, 2),
      status: 0 // 默认为待执行状态
    })
    deviceList.value = []
    selectedDevice.value = null
    formVisible.value = true
  }

  // 打开编辑任务对话框
  const handleEdit = async (row) => {
    try {
      const response = await taskApi.getTaskDetail(row.id)
      Object.assign(taskForm, response.data)
      // 如果有设备ID，尝试获取设备信息并设置设备类型
        if (row.deviceId) {
          try {
            const deviceDetail = await deviceApi.getDeviceDetail(row.deviceId)
            const deviceData = {
              ...deviceDetail.data,
              name: deviceDetail.data.name || deviceDetail.data.deviceName || deviceDetail.data.device_id || `设备${deviceDetail.data.id}`
            }
            taskForm.deviceType = deviceData.deviceType
            selectedDevice.value = deviceData
            await fetchDeviceList(deviceData.deviceType)
          } catch (err) {
            console.error('获取设备详情失败:', err)
            taskForm.deviceType = ''
            deviceList.value = []
            selectedDevice.value = null
          }
        } else {
          taskForm.deviceType = ''
          deviceList.value = []
          selectedDevice.value = null
        }
      formVisible.value = true
    } catch (error) {
      console.error('获取任务详情失败:', error)
      ElMessage.error('获取任务详情失败')
    }
  }

  // 提交任务表单
  const handleSubmit = async () => {
    formLoading.value = true
    try {
      if (taskForm.id) {
        await taskApi.updateTask(taskForm)
        ElMessage.success('更新任务成功')
      } else {
        await taskApi.addTask(taskForm)
        ElMessage.success('添加任务成功')
      }
      formVisible.value = false
      fetchTaskList()
    } catch (error) {
      console.error('保存任务失败:', error)
      ElMessage.error('保存任务失败')
    } finally {
      formLoading.value = false
    }
  }

  // 删除任务
  const handleDelete = async (id) => {
    try {
      await ElMessageBox.confirm('确定要删除该任务吗？', '提示', {
        type: 'warning'
      })
      await taskApi.deleteTask(id)
      ElMessage.success('删除任务成功')
      fetchTaskList()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('删除任务失败:', error)
        ElMessage.error('删除任务失败')
      }
    }
  }

  // 批量删除任务
  const handleBatchDelete = async (selectedRows) => {
    if (selectedRows.length === 0) {
      ElMessage.warning('请选择要删除的任务')
      return
    }
    
    try {
      await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.length} 个任务吗？`, '提示', {
        type: 'warning'
      })
      const ids = selectedRows.map(row => row.id)
      await taskApi.batchDeleteTasks(ids)
      ElMessage.success('批量删除任务成功')
      fetchTaskList()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('批量删除任务失败:', error)
        ElMessage.error('批量删除任务失败')
      }
    }
  }

  // 执行任务
  const handleExecute = async (id) => {
    try {
      await ElMessageBox.confirm('确定要执行该任务吗？', '提示', {
        type: 'warning'
      })
      await taskApi.executeTask(id)
      ElMessage.success('任务执行成功')
      fetchTaskList()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('执行任务失败:', error)
        ElMessage.error('执行任务失败')
      }
    }
  }

  // 批量执行任务
  const handleBatchExecute = async (selectedRows) => {
    if (selectedRows.length === 0) {
      ElMessage.warning('请选择要执行的任务')
      return
    }
    
    try {
      await ElMessageBox.confirm(`确定要执行选中的 ${selectedRows.length} 个任务吗？`, '提示', {
        type: 'warning'
      })
      const ids = selectedRows.map(row => row.id)
      await taskApi.batchExecuteTasks(ids)
      ElMessage.success('批量执行任务成功')
      fetchTaskList()
    } catch (error) {
      if (error !== 'cancel') {
        console.error('批量执行任务失败:', error)
        ElMessage.error('批量执行任务失败')
      }
    }
  }

  // 获取任务状态显示
  const getStatusDisplay = (status) => {
    return taskStatusMap[status] || { label: '未知', type: 'info' }
  }

  // 格式化参数显示
  const formatParameters = (parameters) => {
    try {
      const params = JSON.parse(parameters)
      return Object.entries(params).map(([key, value]) => `${key}: ${value}`).join(', ')
    } catch {
      return parameters
    }
  }

  return {
    // 状态
    taskList,
    loading,
    total,
    queryParams,
    taskForm,
    formVisible,
    formLoading,
    deviceList,
    deviceLoading,
    selectedDevice,
    
    // 常量
    taskStatusMap,
    taskTypeOptions,
    deviceTypeOptions,
    
    // 方法
    fetchTaskList,
    fetchDeviceList,
    handleSearch,
    handleReset,
    handleAdd,
    handleEdit,
    handleSubmit,
    handleDelete,
    handleBatchDelete,
    handleDeviceTypeChange,
    handleDeviceChange,
    handleExecute,
    handleBatchExecute,
    getStatusDisplay,
    formatParameters
  }
}